<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Anggota Tim</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .modal, .toast { transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease; }
        .modal.hidden, .toast.hidden { opacity: 0; visibility: hidden; transform: translateY(20px); }
        .status-belum-dikerjakan { background-color: #f3f4f6; color: #374151; }
        .status-dikerjakan { background-color: #fef9c3; color: #854d0e; }
        .status-revisi { background-color: #FF0000; color: #FFFFFF; }
        .status-selesai { background-color: #dcfce7; color: #166534; }
        .deadline-urgent { background-color: #FF0000; color: #FFFFFF; }
        .deadline-soon { background-color: #fef08a; }
        .deadline-passed { color: #9ca3af; text-decoration: line-through; }
    </style>
</head>
<body class="bg-gray-100 text-gray-800">

    <div id="app-container">
        <!-- Initial Login View -->
        <div id="login-view" class="h-screen flex justify-center items-center">
            <div class="bg-white p-8 rounded-lg shadow-lg w-full max-w-sm">
                <h1 class="text-2xl font-bold text-center mb-6">Login Anggota Tim</h1>
                <form id="loginForm">
                    <div class="mb-4">
                        <label for="teamMemberName" class="block text-sm font-medium text-gray-700 mb-2">Masukkan Nama Anda</label>
                        <input type="text" id="teamMemberName" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required placeholder="Contoh: Ubed">
                    </div>
                    <button type="submit" class="w-full bg-indigo-600 text-white font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-indigo-700">Masuk</button>
                </form>
            </div>
        </div>

        <!-- Main Dashboard View (hidden by default) -->
        <div id="dashboard-view" class="hidden">
             <div class="container mx-auto p-4 md:p-8">
                <header class="mb-6 flex flex-col md:flex-row justify-between items-center">
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900">Tugas Anda</h1>
                        <p class="text-gray-600 mt-1">Selamat datang, <span id="welcomeName" class="font-bold"></span>!</p>
                    </div>
                    <button id="logoutBtn" class="mt-4 md:mt-0 bg-red-500 text-white font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-red-600">Logout</button>
                </header>
                
                <!-- Filter Controls -->
                <div class="mb-4 p-4 bg-white rounded-lg shadow-sm flex flex-col md:flex-row gap-4 items-center">
                    <h3 class="font-semibold text-gray-700">Filter Deadline:</h3>
                    <div class="flex-grow w-full md:w-auto">
                        <label for="dateFilter" class="sr-only">Filter Tanggal</label>
                        <input type="date" id="dateFilter" class="w-full bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5">
                    </div>
                    <button id="resetFiltersBtn" class="w-full md:w-auto bg-gray-200 text-gray-700 font-semibold py-2 px-4 rounded-lg hover:bg-gray-300">Reset Filter</button>
                </div>

                <div class="bg-white rounded-lg shadow-lg overflow-x-auto">
                    <table class="w-full text-sm text-left text-gray-600">
                        <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3">No.</th>
                                <th scope="col" class="px-6 py-3">File / Judul</th>
                                <th scope="col" class="px-6 py-3">File Asli</th>
                                <th scope="col" class="px-6 py-3">Admin</th>
                                <th scope="col" class="px-6 py-3">Deadline</th>
                                <th scope="col" class="px-6 py-3">Status</th>
                                <th scope="col" class="px-6 py-3">Catatan Owner</th>
                                <th scope="col" class="px-6 py-3 text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="tasksTableBody">
                            <!-- Tasks will be rendered here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Submit Work Modal -->
    <div id="submitModal" class="modal hidden fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center p-4">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-lg p-6" onclick="event.stopPropagation()">
            <h2 class="text-2xl font-bold mb-4">Serahkan Hasil Kerja</h2>
            <p class="text-sm text-gray-600 mb-4">Tempelkan link (Google Drive, Dropbox, dll) dari file hasil kerja Anda di bawah ini.</p>
            <form id="submitWorkForm">
                <input type="hidden" id="submitProjectId">
                <div>
                    <label for="fileLink" class="block mb-2 text-sm font-medium text-gray-900">Link Hasil Kerja</label>
                    <input type="url" id="fileLink" placeholder="https://docs.google.com/..." class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                </div>
                <div class="flex justify-end gap-4 mt-6">
                    <button type="button" id="cancelSubmitBtn" class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">Batal</button>
                    <button type="submit" class="py-2 px-4 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700">Kirim</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="toast" class="toast hidden fixed bottom-5 right-5 flex items-center w-full max-w-xs p-4 space-x-4 text-gray-500 bg-white divide-x divide-gray-200 rounded-lg shadow" role="alert">
        <div id="toast-message" class="text-sm font-normal">Message</div>
    </div>

    <script type="module">
        // --- Firebase Module Imports ---
        import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
        import { getFirestore, collection, doc, query, where, onSnapshot, updateDoc, serverTimestamp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";
        import { getAuth, signInAnonymously, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";

        // --- Global State ---
        let db, auth;
        let tasks = [];
        let loggedInTeamMember = null;
        let currentDateFilter = '';
        let toastTimeout;

        // --- DOM Elements ---
        const appContainer = document.getElementById('app-container');
        const loginView = document.getElementById('login-view');
        const dashboardView = document.getElementById('dashboard-view');
        const loginForm = document.getElementById('loginForm');
        let tasksTableBody, welcomeName, logoutBtn, dateFilter, resetFiltersBtn;
        const submitModal = document.getElementById('submitModal');
        const submitWorkForm = document.getElementById('submitWorkForm');
        const cancelSubmitBtn = document.getElementById('cancelSubmitBtn');
        const toast = document.getElementById('toast');
        const toastMessage = document.getElementById('toast-message');

        // --- UI Functions ---
        function showToast(message, type = 'success') {
            if (!toast || !toastMessage) return;
            clearTimeout(toastTimeout);
            toastMessage.textContent = message;
            toast.className = 'toast fixed bottom-5 right-5 flex items-center w-full max-w-xs p-4 space-x-4 rounded-lg shadow';
            if (type === 'success') {
                toast.classList.add('bg-green-100', 'text-green-800');
            } else {
                toast.classList.add('bg-red-100', 'text-red-800');
            }
            toast.classList.remove('hidden');
            toastTimeout = setTimeout(() => { toast.classList.add('hidden'); }, 3000);
        }
        
        function renderErrorState(title, message, details = '') {
            appContainer.innerHTML = `<div class="p-4 text-center text-red-700 bg-red-100 h-screen flex flex-col justify-center items-center">
                <h1 class="text-xl font-bold">${title}</h1>
                <p class="mt-2">${message}</p>
                <p class="mt-1 text-sm text-gray-600">${details}</p>
            </div>`;
        }
        
        function showDashboard(name) {
            loggedInTeamMember = name;
            loginView.classList.add('hidden');
            dashboardView.classList.remove('hidden');

            // Assign elements only available in dashboard view
            welcomeName = document.getElementById('welcomeName');
            logoutBtn = document.getElementById('logoutBtn');
            tasksTableBody = document.getElementById('tasksTableBody');
            dateFilter = document.getElementById('dateFilter');
            resetFiltersBtn = document.getElementById('resetFiltersBtn');

            welcomeName.textContent = name;
            
            // Add listeners for dashboard elements
            logoutBtn.addEventListener('click', showLogin);
            dateFilter.addEventListener('change', () => {
                currentDateFilter = dateFilter.value;
                renderTasks();
            });
            resetFiltersBtn.addEventListener('click', () => {
                dateFilter.value = '';
                currentDateFilter = '';
                renderTasks();
            });

            listenForTasks(name);
        }

        function showLogin() {
            loggedInTeamMember = null;
            currentDateFilter = '';
            loginView.classList.remove('hidden');
            dashboardView.classList.add('hidden');
            document.getElementById('teamMemberName').value = '';
        }

        // --- Application Logic ---
        function listenForTasks(teamMemberName) {
            const appId = 'standalone-parafrase-app';
            const projectsCollectionRef = collection(db, `artifacts/${appId}/public/data/projects`);
            const q = query(projectsCollectionRef, where("teamMember", "==", teamMemberName));
            
            onSnapshot(q, (snapshot) => {
                tasks = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
                renderTasks();
            }, (error) => {
                console.error("Gagal mengambil tugas: ", error);
                showToast("Gagal memuat daftar tugas.", "error");
            });
        }
        
        function getStatusClass(status) {
            const statusMap = {
                'Belum Dikerjakan': 'status-belum-dikerjakan', 
                'Dikerjakan': 'status-dikerjakan',
                'Revisi': 'status-revisi', 
                'Selesai': 'status-selesai',
            };
            return statusMap[status] || 'status-belum-dikerjakan';
        }
        
        function renderTasks() {
            if (!tasksTableBody) return;
            tasksTableBody.innerHTML = '';
            
            const filteredTasks = tasks.filter(task => {
                const dateMatch = !currentDateFilter || (task.deadline && task.deadline.startsWith(currentDateFilter));
                return dateMatch;
            });


            if (filteredTasks.length === 0) {
                tasksTableBody.innerHTML = `<tr><td colspan="8" class="text-center p-8 text-gray-500">Tidak ada tugas yang cocok dengan filter.</td></tr>`;
                return;
            }

            filteredTasks.sort((a,b) => (new Date(a.deadline) > new Date(b.deadline)) ? 1 : -1)
                 .forEach(task => {
                const tr = document.createElement('tr');
                tr.className = "bg-white border-b hover:bg-gray-50";

                const deadlineDate = task.deadline ? new Date(task.deadline).toLocaleString('id-ID', {
                    weekday: 'long',
                    year: 'numeric', month: 'long', day: 'numeric',
                    hour: '2-digit', minute: '2-digit'
                }).replace(/\./g, ':').replace(' pukul ', ', ') : 'N/A';
                
                const isCompleted = task.status === 'Selesai' || task.status === 'Lunas';

                const originalFileLinkHTML = task.originalFileLink
                    ? `<a href="${task.originalFileLink}" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">Buka File</a>`
                    : `<span class="text-gray-400">-</span>`;

                tr.innerHTML = `
                    <td class="px-6 py-4 font-bold">${task.orderNumber || ''}</td>
                    <td class="px-6 py-4 font-medium text-gray-900">${task.fileName}</td>
                    <td class="px-6 py-4">${originalFileLinkHTML}</td>
                    <td class="px-6 py-4">${task.adminName || ''}</td>
                    <td class="px-6 py-4 deadline-cell">${deadlineDate}</td>
                    <td class="px-6 py-4">
                         <select class="status-select border-0 rounded-lg text-sm p-1 cursor-pointer" data-id="${task.id}">
                            <option value="Belum Dikerjakan" ${task.status === 'Belum Dikerjakan' ? 'selected' : ''}>Belum Dikerjakan</option>
                            <option value="Dikerjakan" ${task.status === 'Dikerjakan' ? 'selected' : ''}>Dikerjakan</option>
                            <option value="Revisi" ${task.status === 'Revisi' ? 'selected' : ''}>Revisi</option>
                            <option value="Selesai" ${task.status === 'Selesai' ? 'selected' : ''}>Selesai</option>
                        </select>
                    </td>
                    <td class="px-6 py-4 max-w-xs truncate" title="${task.notes || ''}">${task.notes || ''}</td>
                    <td class="px-6 py-4 text-center">
                        <button class="submit-btn bg-blue-500 hover:bg-blue-600 text-white text-xs font-bold py-1 px-2 rounded" data-id="${task.id}">
                            Serahkan Hasil
                        </button>
                         <a href="${task.fileHasilKerja || '#'}" target="_blank" class="text-blue-600 hover:underline ${!task.fileHasilKerja ? 'hidden' : ''}">Lihat Hasil</a>
                    </td>
                `;

                // Deadline styling
                const deadlineCell = tr.querySelector('.deadline-cell');
                const now = new Date();
                const deadline = task.deadline ? new Date(task.deadline) : null;
                const isDone = task.status === 'Selesai';
                if (deadline && !isDone) {
                    const diffHours = (deadline.getTime() - now.getTime()) / (1000 * 60 * 60);
                    if (diffHours < 0) deadlineCell.classList.add('deadline-passed');
                    else if (diffHours <= 24) deadlineCell.classList.add('deadline-urgent');
                    else if (diffHours <= 72) deadlineCell.classList.add('deadline-soon');
                }

                const statusSelect = tr.querySelector('.status-select');
                statusSelect.className = 'status-select border-0 rounded-lg text-sm p-1 cursor-pointer ' + getStatusClass(task.status);
                statusSelect.addEventListener('change', (e) => updateTaskStatus(e.target.dataset.id, e.target.value));

                const submitBtn = tr.querySelector('.submit-btn');
                if(submitBtn) {
                   submitBtn.addEventListener('click', () => openSubmitModal(task.id));
                }

                tasksTableBody.appendChild(tr);
            });
        }
        
        async function updateTaskStatus(id, newStatus) {
            const appId = 'standalone-parafrase-app';
            const projectRef = doc(db, `artifacts/${appId}/public/data/projects`, id);
            try {
                 await updateDoc(projectRef, { status: newStatus, updatedAt: serverTimestamp() });
                 showToast('Status berhasil diperbarui!', 'success');
            } catch(error) {
                console.error("Gagal memperbarui status: ", error);
                showToast('Gagal memperbarui status.', 'error');
            }
        }
        
        function openSubmitModal(projectId) {
            document.getElementById('submitProjectId').value = projectId;
            submitModal.classList.remove('hidden');
        }

        function closeSubmitModal() {
            submitWorkForm.reset();
            submitModal.classList.add('hidden');
        }

        async function handleWorkSubmit(e) {
            e.preventDefault();
            const projectId = document.getElementById('submitProjectId').value;
            const fileLink = document.getElementById('fileLink').value;

            const appId = 'standalone-parafrase-app';
            const projectRef = doc(db, `artifacts/${appId}/public/data/projects`, projectId);

            try {
                await updateDoc(projectRef, {
                    fileHasilKerja: fileLink,
                    status: 'Selesai', // Automatically set status to 'Selesai' when work is submitted
                    updatedAt: serverTimestamp()
                });
                showToast('Hasil kerja berhasil diserahkan!', 'success');
                closeSubmitModal();
            } catch (error) {
                console.error("Gagal menyerahkan hasil: ", error);
                showToast('Gagal menyerahkan hasil kerja.', 'error');
            }
        }


        // --- Entry Point ---
        document.addEventListener('DOMContentLoaded', () => {
            try {
                // Konfigurasi ini HARUS diganti dengan milik Anda agar berfungsi di luar Gemini
                const standaloneConfig = {
                    apiKey: "AIzaSyYOUR_API_KEY_HERE",
                    authDomain: "your-project-id.firebaseapp.com",
                    projectId: "your-project-id",
                    storageBucket: "your-project-id.appspot.com",
                    messagingSenderId: "your-sender-id",
                    appId: "your-app-id"
                };

                let firebaseConfig = standaloneConfig;
                
                if (typeof __firebase_config !== 'undefined' && __firebase_config) {
                    firebaseConfig = JSON.parse(__firebase_config);
                } else if (standaloneConfig.apiKey === "AIzaSyYOUR_API_KEY_HERE") {
                    renderErrorState("Konfigurasi Belum Diatur", "Anda perlu menyalin konfigurasi proyek Firebase Anda ke dalam file HTML ini agar dapat berfungsi.", "Lihat variabel 'standaloneConfig'.");
                    return;
                }

                const app = initializeApp(firebaseConfig);
                db = getFirestore(app);
                auth = getAuth(app);
                
                // Always sign in for a session
                onAuthStateChanged(auth, (user) => {
                    if(!user){
                       signInAnonymously(auth).catch(err => console.error("Gagal sign-in anonim:", err));
                    }
                });
                
                // Event Listeners
                loginForm.addEventListener('submit', (e) => {
                    e.preventDefault();
                    const name = document.getElementById('teamMemberName').value.trim();
                    if(name) showDashboard(name);
                });

                submitWorkForm.addEventListener('submit', handleWorkSubmit);
                cancelSubmitBtn.addEventListener('click', closeSubmitModal);


            } catch (error) {
                console.error("CRITICAL ERROR on startup:", error);
                renderErrorState("Gagal Memuat Aplikasi", "Tidak dapat terhubung ke database.", error.message);
            }
        });
    </script>
</body>
</html>
